﻿


crucible.TreeNode = function (data) {
    crucible.Node.call(this, data);


    var self = this;

    this.parent = null;
    this.Children = ko.observableArray();
    
    this.elementId = null;

    this.IsFocused = ko.observable(false);
    this.IsEditing = ko.computed(function () {
        return !self.Published() && self.IsFocused();
    });
    this.IsDirty = ko.observable(false);
    this.Action = ko.computed(function () {
        return self.Published() || self.AddedBy().UserId != crucible.userId ? "View" : "Edit";
    });
    

    this.OtherParents = ko.observableArray();

    this.cloneOf = data.cloneOf;
    this.cloneNum = data.cloneNum;

    this.NodeCss = ko.computed(function () {

        if (self.el) {
            self.el.removeClass("nType1 nType2 nType3 nType4");
        }
        var styles = {};
        styles["nType" + self.Type()] = true;
        styles.nPublished = self.Published();
        styles.nClone = self.cloneOf;
        styles.assertionBox = true;
        return styles;
    });

    this.colspan = ko.computed(function () {
        return self.IsFocused() ? 2 : 1;
    });
    this.rowspan = ko.computed(function () {
        return self.IsFocused() ? (self.Published() ? 2 : 4) : 1;
    });

    this.IsFertile = ko.computed(function () {
        if (self.Type() == crucible.NodeType.assertion) return true;

        if (self.Type() == crucible.NodeType.interpretation || self.Type() == crucible.NodeType.source) {
            return self.Source();
        }

        return false;
    });

    this.Type.subscribe(function (newType) {
        if (self.cloneList) {
            for (var i = 0; i < self.cloneList.length; i++) {
                self.cloneList[i].Type(newType);
            }
        }
    });
};


crucible.TreeNode.prototype = Object.create(crucible.Node.prototype);

crucible.TreeNode.prototype.freshData = function (data, parents) {
    crucible.Node.prototype.freshData.call(this, data);
    this.setOtherParents(parents);
};

crucible.TreeNode.prototype.setOtherParents = function (parents) {
    if (parents) {
        this.OtherParents.removeAll();
        for (var i = 0; i < parents.length; i++) {
            if (!this.parent || parents[i].Id != this.parent.Id) {
                this.OtherParents.push(parents[i]);
            }
        }
    }
};

crucible.TreeNode.prototype.clone = function (cloneNum) {
    var clone = new crucible.TreeNode({
        Id: this.Id,
        Title: this.Title(),
        Type: this.Type(),
        Published: this.Published(),
        cloneOf: this,
        cloneNum: cloneNum
    });

    return clone;
};

crucible.TreeNode.prototype.setEl = function() {
    if (this.elementId) {
        this.el = $("#" + this.elementId).on("mousedown", function (e) {
            e.stopPropagation();
        });
    }
};